package com.ruoyi.crm.Listener;

import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.ruoyi.common.config.DDConstant;
import com.ruoyi.common.enums.flow.FlowTypeEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.dd.MessageUtil;
import com.ruoyi.common.utils.flow.FlowDTO;
import com.ruoyi.crm.strategy.CrmOrderContext;
import com.ruoyi.crm.strategy.CrmOrderFlowStrategy;
import com.taobao.api.ApiException;
import com.warm.flow.core.entity.Instance;
import com.warm.flow.core.listener.Listener;
import com.warm.flow.core.listener.ListenerVariable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.Map;

/**
 * 项目立项启动监听器
 *
 * @author 陈彬彬
 * @date 2023-04-11
 */
@Component
@Slf4j
public class CrmOrderRegisterListener implements Listener {

    @Value("${approver.userId}")
    private String userId;

    @Autowired
    private CrmOrderContext crmOrderContext;

    /**
     * 项目立项发送钉钉通知审批人
     *
     * @author 陈彬彬
     * @date 2023-04-11
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void notify(ListenerVariable variable) {
        log.error("开始监听器;{}", variable);
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("markdown");
        msg.setMarkdown(new OapiMessageCorpconversationAsyncsendV2Request.Markdown());
        msg.getMarkdown().setTitle("项目立项审批提醒");
        Instance instance = variable.getInstance();
        String text = this.builder(instance);
        msg.getMarkdown().setText(text);
        //发送钉钉 工作通知
        try {
            MessageUtil.send(userId, msg);
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }

    }

    private String builder(Instance instance){
        Long definitionId = instance.getDefinitionId();
        String businessId = instance.getBusinessId();
        String name = FlowTypeEnum.getNameByDefinitionId(definitionId.toString());
        CrmOrderFlowStrategy orderFlowService = crmOrderContext.getOrderFlowService(name);
        FlowDTO flowDTO = orderFlowService.conversionObjByLocal(businessId);

        StringBuilder text = new StringBuilder();
        text.append("## " + flowDTO.getSubmitUser() + "提交的商机立项申请，请审批！");
        text.append("  \n  ");
        Map<String, Object> businessValue = flowDTO.getBusinessValue();
        Iterator<Map.Entry<String, Object>> iterator = businessValue.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            text.append(entry.getKey() + ": " + entry.getValue());
            text.append("  \n  ");
        }

        text.append("  \n  ");
        text.append("[立即查看](" + DDConstant.DD_FRONT_URL + DDConstant.FRONT_URL_HOST + "flow/todo)");
        return text.toString();
    }
}
